package com.pilot.game.service;

import com.pilot.game.config.ApplicationProperties;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * UploadFileUtil
 *
 * @author yhq
 * @version 2017/9/21 下午3:26
 */
@Service
public class FileUploadService {

    Logger log = LoggerFactory.getLogger(FileUploadService.class);

    private final ApplicationProperties.QiNiu properties;

    public FileUploadService(ApplicationProperties properties) {
        this.properties = properties.getQiNiu();
    }

    public String uploadFile(byte[] file, String fileName) {

        String fileUrl = properties.getUrl();
        try {
            fileName = properties.getFilePath() + (StringUtils.isNoneBlank(fileName) ? fileName : UUID.randomUUID().toString());
            //密钥配置
            Auth auth = Auth.create(properties.getAccessKey(), properties.getSecretKey());
            Zone z = Zone.autoZone();
            Configuration c = new Configuration(z);

            //创建上传对象
            UploadManager uploadManager = new UploadManager(c);

            //简单上传，使用默认策略，只需要设置上传的空间名就可以了
            String uploadToken = auth.uploadToken(properties.getBucketName());
            //调用put方法上传
            uploadManager.put(file, fileName, uploadToken);
            fileUrl += fileName;
        } catch (QiniuException e) {
            log.error(e.getMessage(), e);
        }
        return fileUrl;
    }


}
